package com.woniuxy.service.impl;

import com.woniuxy.dao.ServerMenuMapper;
import com.woniuxy.dao.ServerSubscribeMapper;
import com.woniuxy.dao.ServersMapper;
import com.woniuxy.dto.ResultChangeServer;
import com.woniuxy.dto.ResultServerDetail;
import com.woniuxy.exception.ErrorException;
import com.woniuxy.pojo.ServerMenu;
import com.woniuxy.pojo.ServerSubscribe;
import com.woniuxy.pojo.Servers;
import com.woniuxy.service.ServerService;


import org.apache.ibatis.javassist.NotFoundException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
@Transactional
public class ServerServiceImpl implements ServerService {

    @Autowired
    private ServerMenuMapper serverMenuMapper;

    @Autowired
    private ServersMapper serversMapper;

    @Autowired
    private ServerSubscribeMapper serverSubscribeMapper;

    @Override
    public List<ServerMenu> findMenu() {
        List<ServerMenu> menus = serverMenuMapper.findMenu(Long.parseLong("0"));
        for (ServerMenu menu : menus) {
            List<ServerMenu> submenus = serverMenuMapper.findMenu(menu.getId());
            menu.setSubmenus(submenus);
        }
        return menus;
    }

    @Override
    public List<ServerMenu> findHotServer() {
        //根据服务分组，在统计使用次数之和，取前三
        List<Long> menusId = serversMapper.findHotServer();
        //根据服务id查服务
        List<ServerMenu> hotServer = serverMenuMapper.findByIds(menusId);
        return hotServer;
    }

    @Override
    public List<Servers> findById(Long serverMenuId) {
        return serversMapper.findByServerMenuId(serverMenuId);
    }

    @Override
    public List<ResultChangeServer> findServersByMenuId(Long serverMenuId) {
        List<ResultChangeServer> serversByMenuId = serversMapper.findServersByMenuId(serverMenuId);
        for (ResultChangeServer resultChangeServer : serversByMenuId) {
            if(resultChangeServer.getServerType() == 0){
                resultChangeServer.setVendorName("小区物业");
            }
        }
        return serversByMenuId;
    }

    @Override
    public ResultServerDetail findProviderByMidAndTypeId(Long mid, Integer typeId,Long id) throws ErrorException {
        ResultServerDetail rsd = null;
        //对type类型进行判断，0去查物业表，1查商家表
        if(typeId == 0){
            //查物业表
            rsd = serversMapper.findProviderByPidAndTypeId(mid,typeId,id);
            rsd.setUserName("物业阿姨");
            return rsd;
        }else if(typeId == 1){
            //查商家表
            rsd = serversMapper.findProviderByMidAndTypeId(mid,typeId,id);
            return rsd;
        }else {
            throw new ErrorException();
        }
    }
    //向预约表中插入数据
    @Override
    public void insertServerSubscribe(ServerSubscribe serverSubscribe) {

        serverSubscribeMapper.insert(serverSubscribe);
    }
}
